package com.camel.base.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.camel.core.exceptions.CustomException;
import lombok.Data;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class MyConnection {
    public Connection connection;

    public Integer id;

    public List<JSONObject> excuteQuery(String sql) throws SQLException {
        Statement statement = this.connection.createStatement();
        ResultSet resultSet = null;
        try {
            resultSet = statement.executeQuery(sql);
        }catch (SQLException e) {
            System.err.println("执行sql异常: " + sql);
            throw new CustomException(e.getMessage());
        }
        ResultSetMetaData md = resultSet.getMetaData();
        int columnCount = md.getColumnCount();
        List<JSONObject> r = new ArrayList<>();
        Map<String, Object> rowData = new HashMap<>();
        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnLabel(i), resultSet.getObject(i));
            }
            String jsonStr = JSONObject.toJSONString(rowData);
            r.add(JSON.parseObject(jsonStr));
        }
        return r;
    }

    public Long excuteQueryForNumber(String sql) throws SQLException {
        Statement statement = this.connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        ResultSetMetaData md = resultSet.getMetaData();
        int columnCount = md.getColumnCount();
        Map<String, Object> rowData = new HashMap<>();
        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                rowData.put(md.getColumnLabel(i), resultSet.getObject(i));
                if("totalnum".equals(md.getColumnLabel(i)) && md.getColumnCount() == 1) {
                    return (Long) resultSet.getObject(i);
                }
            }
        }
        return 1L;
    }

    public int excute(String sql) throws SQLException {
        Statement statement = this.connection.createStatement();
        boolean res = statement.execute(sql);

        return res ? 1 : 0;
    }



}
